# Thanks to https://github.com/VOICEVOX/voicevox
# We use Voicevox to read Japanese sentences and words

import requests

server_url = 'http://127.0.0.1:50021'
text_url = f"{server_url}/audio_query?speaker=1"
synthesis_url = f"{server_url}/synthesis?speaker=2"


class Audio:

    def __init__(self, text):
        self.text = text

    def get_json(self):
        resp = requests.post(text_url, params={'text': self.text})
        return resp.json()

    def get_file(self): # 二进制数据，尚未保存为文件的状态
        resp = requests.post(synthesis_url, headers={"Content-Type": "application/json"}, json=self.get_json())
        if resp.status_code == 200:
            return resp.content

    def save(self):        
        with open('audio.wav', 'wb') as audio_file:
            audio_file.write(self.get_file())
    

if __name__ == '__main__':
    test = 'バカ！変態！うるさい！もう知らない！'
    au = Audio(test)
    au.save()
    import os
    os.system('afplay audio.wav') # 无图形界面的音频播放器
